package team.se.tms.service.impl;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import team.se.tms.constant.DateFormatConstant;
import team.se.tms.constant.RoleConstant;
import team.se.tms.dao.impl.DaoImpl;
import team.se.tms.dto.*;
import team.se.tms.exception.ParamException;
import team.se.tms.exception.SelectException;
import team.se.tms.factory.ModelFactory;
import team.se.tms.po.SelectCourseInfo;
import team.se.tms.po.StudentInfo;
import team.se.tms.po.UserInfo;
import team.se.tms.service.StudentInfoService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service("studentInfoService")
public class StudentInfoServiceImpl implements StudentInfoService {
    @Autowired
    DaoImpl dao;
    /**
     * 查询学生的基本详情
     *
     * @param userId 用户Id
     * @return StudentBasicDetail 学生基本详情
     * @throws Exception 异常
     * @create on 2019/1/2 by sunddly
     */
    @Override
    public StudentBasicDetail getStudentBasic(String userId) throws Exception {
        StudentBasicDetail studentBasicDetail = dao.selectOne("StudentInfoMapper.selectStudentBasicByUserId",userId);
        return studentBasicDetail;
    }
    /**
     * 查询学生的所有授课的项目详情
     *
     * @param studentId 学生Id
     * @param page
     * @return List<TeachCourseProjectDetail>
     * @throws Exception 异常
     * @create on 2019/1/2 by sunddly
     */
    @Override
    public List<TeachCourseProjectDetail> listTeachCourseProjcet(String studentId,Page page) throws Exception {
        ParameterPage parameterPage = new ParameterPage();
        parameterPage.put("studentId",studentId);
        parameterPage.setPage(page);
        //System.out.println("())))))))))))))))))))))"+dao.selectList("TeachCourseInfoMapper.selectCourseProjectsByStuId",parameterPage).size());
        return dao.selectList("TeachCourseInfoMapper.selectCourseProjectsByStuId",parameterPage);
    }

    @Override
    public List<StudentInfo> listGroupStudentInfos(String projectId) throws Exception {
        return dao.selectList("StudentInfoMapper.selectStudentInfosByProjectId",projectId);
    }

    /**
     * @create on 2018/12/24 by argentum
     *
     * @param teachCourseId
     * @return
     */
    @Override
    public List<StudentInfo> listStudentInfos (String teachCourseId) throws Exception{
        return  dao.selectList("StudentInfoMapper.selectStudentInfoByTeachCourseId",teachCourseId);
    }

    /**
     * 根据selectCourseInfo查询该学生是否选课以及该学生的信息
     * @param selectCourseInfo
     * @return
     * @throws Exception
     * @create on 2018/12/29 by qingx
     */
    @Override
    public StudentInfo getStudentInfo(SelectCourseInfo selectCourseInfo) throws Exception {
        StudentInfo studentInfo = dao.selectOne("StudentInfoMapper.selectStudentInfoByStuId",selectCourseInfo.getStuId());
        if (studentInfo == null){
            throw new SelectException("学号错误");
        }
        SelectCourseInfo select = dao.selectOne("SelectCourseInfoMapper.selectStudentInfoByStuIdAndTeachCourseId",selectCourseInfo);
        if (select == null){
            throw new SelectException("该学生尚未选课");
        }
        return studentInfo;
    }

    /**
     * 查询学生列表
     * @param page
     * @return
     * @throws Exception
     * @create on 2018/12/29 by qingx
     */
    @Override
    public List<StudentBasicDetail> listAllStudentBasicDetails(Page page) throws Exception {
        return  dao.selectList("StudentInfoMapper.selectAllStudentBasicDetails",page);
    }

    /**
     * 录入学生信息
     *
     * @param addType 添加学生类型
     * @param studentInfo 学生信息
     * @return
     * @throws Exception 异常
     * @create on 2018/12/29 by qingx
     */
    @Override
    public String savaStudentInfo(String addType, StudentInfo studentInfo) throws Exception {
        int updateResult = 0;
        UserInfo user = new UserInfo();
        if(addType.equals("addNewUser")){
            //生成用户实例
            user = ModelFactory.createUserInfo(RoleConstant.STUDENT);
            studentInfo.setUserId(user.getUserId());
            System.out.println("******************************************"+user);
            updateResult = (int) dao.insert("UserInfoMapper.insertUserInfo",user);
        }else if(addType.equals("addExistingUser")){
            user.setUserId(studentInfo.getUserId());
            user.setRoleId(RoleConstant.STUDENT);
            System.out.println("******************************************"+user);
            updateResult = (int) dao.update("UserInfoMapper.updateUserInfoByUserId",user);
        }
        if(updateResult != 0){
            int result = (int) dao.insert("StudentInfoMapper.insertStudentInfo", studentInfo);
            if(result != 0){
                return studentInfo.getUserId();
            }
        }
        return null;
    }

    /**
     * 修改学生信息
     *
     * @param studentInfo 学生信息
     * @return 添加成功或失败
     * @throws Exception
     * @create on 2018/12/30 by qingx
     */
    @Override
    public boolean modifyStudentInfo(StudentInfo studentInfo) throws Exception {
        int result = (int) dao.update("StudentInfoMapper.updateStudentInfoByStuId", studentInfo);
        if (result != 0){
            return true;
        }
        return false;
    }

    /**
     * 批量上传学生信息
     *
     * @return json字符串
     * @throws Exception 异常
     * @create on 2018/12/30 by qingx
     */
    @Override
    public boolean saveStudentInfos(MultipartFile multipartFile) throws Exception {
        if(multipartFile==null){
            throw new ParamException("文件不能为空");
        }
        SimpleDateFormat sdfBirth = new SimpleDateFormat(DateFormatConstant.DATE);
        SimpleDateFormat sdfEntryYear = new SimpleDateFormat(DateFormatConstant.YEAR);
        List<StudentInfo> studentInfos = new ArrayList<>();
        List<UserInfo> userInfos = new ArrayList<>();
        try {
            //获得excel文件对象
            Workbook wb = Workbook.getWorkbook(multipartFile.getInputStream());
            //获取文件的指定工作表
            Sheet s = wb.getSheet(0);
            //第一行不要
            for(int i=1;i<s.getRows();i++)
            {
                Cell[] row = s.getRow(i);
                //填充数据
                StudentInfo studentInfo = new StudentInfo(row[0].getContents(), row[1].getContents(),
                        row[2].getContents(), sdfBirth.parse(row[3].getContents()),
                        sdfEntryYear.parse(row[4].getContents()), row[5].getContents(), row[6].getContents(),
                        Integer.parseInt(row[7].getContents()), row[8].getContents(), null, row[9].getContents());
                UserInfo userInfo = ModelFactory.createUserInfo(RoleConstant.STUDENT);
                userInfos.add(userInfo);
                studentInfo.setUserId(userInfo.getUserId());
                studentInfos.add(studentInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(studentInfos);
        int result = dao.insert("UserInfoMapper.insertUserInfos",userInfos);
        if (result != 0){
            int stuResult = dao.insert("StudentInfoMapper.insertStudentInfos",studentInfos);
            if (stuResult != 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 批量修改学生挂科数
     *
     * @return json字符串
     * @throws Exception 异常
     * @create on 2018/12/31 by qingx
     */
    @Override
    public boolean modifyStudentFailNums(MultipartFile multipartFile) throws Exception {
        if(multipartFile==null){
            throw new ParamException("文件不能为空");
        }
        List<StudentInfo> studentInfos = new ArrayList<>();
        try {
            //获得excel文件对象
            Workbook wb = Workbook.getWorkbook(multipartFile.getInputStream());
            //获取文件的指定工作表
            Sheet s = wb.getSheet(0);
            //第一行不要
            for(int i=1;i<s.getRows();i++)
            {
                Cell[] row = s.getRow(i);
                //填充数据
                StudentInfo studentInfo = new StudentInfo(row[0].getContents(),null,
                        null, null, null, null,null,
                        Integer.parseInt(row[7].getContents()), null, null, null);
                studentInfos.add(studentInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(studentInfos);
        int result =  dao.insert("StudentInfoMapper.updateStudentFailNums",studentInfos);
        if (result != 0){
            return true;
        }
        return false;
    }
}
